/**
 * @description jwt中间件
 * @author 盘古他爹
 */

import { JWT } from "../utils/jwt"
import { C, N} from "../config/commonTypes";
import { Restfull } from "../config/resModel";
import { TokenNotFound,ErrorTokenType,ErrorToken } from "../config/resCodeMsg"
const jwtAuth = async(ctx:C,next:N) => {
    let token = ctx.request.header.authorization
  // console.log(ctx.request.body);
  if (!token) {
    ctx.body = Restfull.faild(TokenNotFound)
    console.log("没有token", ctx.request.header);

    return
  }
  console.log("token:", token);
  if(!token.startsWith("Bearer ")) {
      //token格式不正确
      ctx.body = Restfull.faild(ErrorTokenType)
      return
  }
  token = token.replace("Bearer ", "")
  //进行比对
      const verifyRes = JWT.JwtVerify(token);
      ctx.userInfo = verifyRes
      console.log("比对结果:", verifyRes);
      if(!verifyRes) {
        ctx.body = Restfull.faild(ErrorToken);
        return
      }
    await next() 
   
     
  
  
}

const  JwtWebSocket = (token: string)=> {
  // console.log(ctx.request.body);
  let res: any = false
  // console.log("token11:", token);

  if (token) {
    token = token.replace("Bearer ", "")
    try {
      // console.log("有token", token);
      var result = JWT.JwtVerify(token)
      // ctx.userInfo as ICtxUser
      if (result) {
        res = result
        return res
      }
    } catch (err) {
      console.error(err);
      return res
    }
  }

  return res

}



export {
    jwtAuth,
    JwtWebSocket
}

